package com.TCP_UDP网络编程.homeWork;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TCP1_client {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        String str = "";
        while(!((str = sc.next()).equals("-1"))){
        bw.write(str);
        bw.newLine();
        bw.flush();
        }
        socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while((str = br.readLine()) != null){
            System.out.println(str);
        }
        br.close();

        socket.close();
        /**bw.close() 和 socket.shutdownOutput() 一起用会报错；
         * 报错信息 java.net.SocketException: Socket is closed 表示在调用 socket.shutdownOutput() 时，
         * 该 socket 已经被关闭。这是因为在执行 bw.close() 时，底层的 OutputStream 也被关闭了，
         * 而 Socket 的输出流一旦关闭，整个 socket 连接会被中断，导致后续调用 socket.shutdownOutput() 时报错。
         *
         * 说人话就是 bw.close把socket的流关闭了，自然socket中断导致关闭， shutdown有关闭了一次，所以会报错；
         */
    }
}
